<template>
  <!--修改计划弹窗-->
  <px-dialog v-model="visible" title="修改计划" width="1200px" destroy-on-close append-to-body @close="handleCancel">
    <px-form ref="editRef" :model="formValue" :rules="rules" label-width="150px">
      <ExecutionCycle :isEdit="true" :form-value="formValue" @change="handelExecutionCycleChange" />
    </px-form>
    <template #footer>
      <div class="dialog-footer">
        <px-button @click="handleCancel">取 消</px-button>
        <px-button type="primary" @click="handleSubmitAuditForm(editRef)">确 定</px-button>
      </div>
    </template>
  </px-dialog>
</template>

<script lang="ts" setup>
import { detailToolInventoryList, editToolInventoryPlanCycle } from "@/api/equip/toolManage";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";
import ExecutionCycle from "./ExecutionCycle.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["closeDialog", "queryTable"]);
// 父级传过来的值
const props = defineProps(["visible", "planId"]);

const visible = computed(() => props.visible);

// 表单校验规则
const rules = computed(() => ({
  execStartDate: [
    {
      required: true,
      message: "请选择开始日期",
      trigger: "change"
    }
  ],
  execEndDate: [
    {
      required: true,
      message: "请选择结束日期",
      trigger: "change"
    }
  ],
  execDuration: [
    {
      required: true,
      message: "请选择执行时长",
      trigger: "blur"
    }
  ],
  taskCreateTime: [
    {
      required: true,
      message: "请选择任务生成并提醒时间",
      trigger: "change"
    }
  ]
}));

const editRef = ref();

const state = reactive<Record<string, any>>({
  formValue: {}
});
const { formValue } = toRefs(state);

const handelExecutionCycleChange = val => {
  Object.assign(formValue.value, val);
};

const handleCancel = () => {
  editRef.value.resetFields();
  emits("closeDialog");
};

watchEffect(async () => {
  if (props.visible) {
    const res = await detailToolInventoryList(props.planId);
    formValue.value = { ...res, execType: "2" };
  }
});

/** 提交按钮 */
const handleSubmitAuditForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await editToolInventoryPlanCycle({ id: props.planId, ...formValue.value });
      PxMessage.success("计划修改成功");
      emits("queryTable");
      handleCancel();
    }
  });
};
</script>
